package com.demo.niodemo;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class NIOFileReadDemo {

	public static void main(String[] args) throws IOException {
		 String fileName =
		 NIOFileReadDemo.class.getClass().getResource("/").getFile()+"/nio-data.txt";
		//String fileName = "d://a.txt";
		long start = System.currentTimeMillis();
		readFileByFileInputStream(fileName);
		long end = System.currentTimeMillis();
		System.out.println("=============");
		System.out.println((end - start) / 1000 / 60);
	}
	
	public static void readFileByFileInputStream(String fileName) throws IOException {
		FileInputStream fis = new FileInputStream(fileName);
		readFileByFileChannel(fis.getChannel());
		fis.close();
	}

	/**
	 * getChannel by java.io.RandomAccessFile
	 * @param fileName
	 * @throws IOException
	 */
	public static void readFileByRandomAccessFile(String fileName) throws IOException {
		RandomAccessFile aFile = new RandomAccessFile(fileName, "r");
		FileChannel inChannel = aFile.getChannel();
		readFileByFileChannel(inChannel);
		aFile.close();
	}

	private static void readFileByFileChannel(FileChannel fileChannel)
			throws IOException {
		CharBuffer cb = CharBuffer.allocate(1024);
		ByteBuffer buf = ByteBuffer.allocate(1024);
		// System.out.println(inChannel.size());
		int bytesRead = fileChannel.read(buf);

		// Java.nio.charset.Charset处理了字符转换问题。它通过构造CharsetEncoder和CharsetDecoder将字符序列转换成字节和逆转换。
		Charset charset = Charset.forName("UTF-8");
		CharsetDecoder decoder = charset.newDecoder();
		while (bytesRead != -1) {
			buf.flip();
			decoder.decode(buf, cb, false);
			cb.flip();
			while (cb.hasRemaining()) {
				// System.out.println(buf.get());
				//输出
				System.out.print(cb.get());
			}
			cb.clear();
			buf.clear();
			bytesRead = fileChannel.read(buf);
		}
		fileChannel.close();
	}

}
